package org.example.dining_philosopher_problem;

public class philosopher extends Thread{

    private chopsticks left;
    private chopsticks right;
    private int index;

    public philosopher(chopsticks left, chopsticks right, int index) {
        this.left = left;
        this.right = right;
        this.index = index;
    }

    public chopsticks getLeft() {
        return left;
    }

    public void setLeft(chopsticks left) {
        this.left = left;
    }

    public chopsticks getRight() {
        return right;
    }

    public void setRight(chopsticks right) {
        this.right = right;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    @Override
    public void run() {

        //防止死锁
        if (this.index%2==0){
            //左撇子
            try {
                synchronized (left){
                    synchronized (right){
                        //使线程睡眠2s，使效果跟明显
                        Thread.sleep(1000);
                        System.out.println(this.index+" 号哲学家进餐完毕！");
                        Thread.sleep(1000);
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else {
            try {
                synchronized (right){
                    synchronized (left){
                        //使线程睡眠2s，使效果跟明显
                        Thread.sleep(1000);
                        System.out.println(this.index+" 号哲学家进餐完毕！");
                        Thread.sleep(1000);
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
